package com.shuimo.emoswxapi.wx.exception;

import com.shuimo.emoswxapi.wx.common.enums.GlobalStatusEnum;
import com.shuimo.emoswxapi.wx.common.util.R;
import com.shuimo.emoswxapi.wx.exception.EmosException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public R validExceptionHandler(Exception e) {
        log.error("执行异常", e);
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            //将错误信息返回给前台
            return R.error(GlobalStatusEnum.PARAM_EXCEPTION.getCode(), exception.getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof EmosException) {
            EmosException exception = (EmosException) e;
            return buildBody(exception);
        } else if (e instanceof UnauthorizedException) {
            GlobalStatusEnum error = GlobalStatusEnum.AUTHORITY_ERROR;
            return buildBody(error);
        } else {
            GlobalStatusEnum error = GlobalStatusEnum.ERROR;
            return buildBody(error);
        }

    }

    private R buildBody(EmosException e) {
        return R.error(e.getCode(), e.getMsg());
    }

    private R buildBody(GlobalStatusEnum globalStatusEnum) {
        return R.error(globalStatusEnum.getCode(), globalStatusEnum.getMsg());
    }


}

